package com.secsbrain.deploy.remote.utils;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;

/**
 * Http工具类
 * 
 * @author zhaoyi
 */
@Component
public class HttpUtils {
    
    /**
     * 功能描述: <br>
     * http get请求
     * 
     * @param url 请求URL
     * @param map 请求参数MAP
     * @return
     */
    public String getRequest(String url, Map<String, Object> map) {
    	HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        GetMethod method = new GetMethod(url);
    	
        try {
            String params = getUrlParamsByMap(map, false);
        	method.setQueryString(params);
        	
        	//TODO appCode待改
        	method.addRequestHeader("appCode", "1111");
        	
            int statusCode = client.executeMethod(method);
            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            return list.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }
        return null;
    }
    
    public static final String ENCODING="UTF-8";

    /**
     * 将 String 转为 map
     * 
     * @param param aa=11&bb=22&cc=33
     * @return
     */
    private static Map<String, Object> getUrlParams(String param) {
        Map<String, Object> map = new HashMap<String, Object>();
        if ("".equals(param) || null == param) {
            return map;
        }
        String[] params = param.split("&");
        for (int i = 0; i < params.length; i++) {
            String[] p = params[i].split("=");
            if (p.length == 2) {
                map.put(p[0], p[1]);
            }
        }
        return map;
    }
   
    /**
     * 将map 转为 string
     * 
     * @param map
     * @return
     * @throws Exception 
     */
    private String getUrlParamsByMap(Map<String, Object> map,
            boolean isSort) throws Exception {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        List<String> keys = new ArrayList<String>(map.keySet());
        if (isSort) {
            Collections.sort(keys);
        }
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            if(!map.containsKey(key)||map.get(key)==null){
                continue;
            }
            Object params=map.get(key);
            if(params.getClass().isArray()){
            	Object[] array = (Object[]) params;
            	for(Object object:array){
            		String value = object.toString();
                    sb.append(key + "=" + URLEncoder.encode(value,ENCODING));
                    sb.append("&");
            	}
            }else{
            	String value = map.get(key).toString();
                sb.append(key + "=" + URLEncoder.encode(value,ENCODING));
                sb.append("&");
            }
            
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.lastIndexOf("&"));
        }
        return s;
    }

    /**
     * 功能描述: <br>
     * http post请求
     * 
     * @param url 请求URL
     * @param jsonStr 请求json参数
     * @return
     */
    public String postRequest(String url, String jsonStr) {
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        PostMethod method = new PostMethod(url);

        try {
            method.setRequestHeader("appCode", "APP_JUIFHY");
            method.setRequestHeader("env", "local");
            method.setRequestHeader("CurTime", String.valueOf((new Date()).getTime() / 1000L));
            method.setRequestHeader("token", "0e247c79bd057e8d1ba51d510e2be8b77fccd734");
            method.setRequestHeader("Content-Type", "application/json");
            
            RequestEntity requestEntity = new StringRequestEntity(jsonStr, "application/json", "UTF-8");
            method.setRequestEntity(requestEntity);

            int statusCode = client.executeMethod(method);
            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            return list.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }

        return null;
    }
    
    /**
     * 功能描述: <br>
     * http post请求
     * 
     * @param url 请求URL
     * @param params 请求参数
     * @return
     */
    public String submitPost(String url, Map<String, String> params) {
    	HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        PostMethod method = new PostMethod(url);
        
        try {
        	if(params!=null){
        		Set<Map.Entry<String, String>> entryseSet=params.entrySet();
            	for (Map.Entry<String, String> entry:entryseSet) {
            		method.setParameter(entry.getKey(), entry.getValue());
        		}
        	}
        	
            int statusCode = client.executeMethod(method);
            
            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            
            if(CollectionUtils.isNotEmpty(list)){
                StringBuffer buffer=new StringBuffer();
                for(String str:list){
                    buffer.append(str + "\n");
                }
                return list.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }

        return null;
    }

    /**
     * 功能描述: <br>
     * http put请求
     * 
     * @param url 请求URL
     * @param jsonStr 请求参数Json串
     * @return
     */
    public String putRequest(String url, String jsonStr) {
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        PutMethod method = new PutMethod(url);

        try {
            RequestEntity requestEntity = new StringRequestEntity(jsonStr, "application/json", "UTF-8");
            method.setRequestEntity(requestEntity);

            int statusCode = client.executeMethod(method);
            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            return list.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }

        return null;
    }

    /**
     * 功能描述: <br>
     * http delete请求
     * 
     * @param url 请求URL
     * @return
     */
    public String deleteRequest(String url) {
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        DeleteMethod method = new DeleteMethod(url);

        try {
            int statusCode = client.executeMethod(method);
            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            return list.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }

        return null;
    }
    
}
